/**
 * @description: 数据中台-任务-任务管理
 * @author: hj
 * @update: hj(2020-01-14)
 */
import React from 'react';
import Container from '@icedesign/container';
import styles from './index.module.scss';
import event from '@/request'
import {Button, Drawer, Form, Input, Message, Pagination, Table, Upload} from '@alifd/next';
import ZgDialog from '@/components/ZgDialog';
import $http from '@/service/Services';
import {Link} from "react-router-dom";

const FormItem = Form.Item;
const formItemLayout = {
    labelCol: {
        span: 7
    },
    wrapperCol: {
        span: 16
    }
};


/**
 * list
 */
class BusinessIntelligenceTaskList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            subjectId: "",
            current: 0,
            mockData: [],
            selectedList: [],
            condition: "",
            visibleUploadZipFileDrawer: false,
            record: {},
            config: {
                data: null,
                visible: false,
                title: "",
                content: ""
            }
        };
        // 当前页数
        this.pageNum = 1;
        // 分页每页显示数据条数
        this.pageSize = 10;
        // 数据总条数
        this.totalNum = 0;
        this.$http = $http;
        this.cancelCall = this.cancelCall.bind(this);
        this.handleClick = this.handleClick.bind(this);
        this.onPageChange = this.onPageChange.bind(this);
        this.getBusinessIntelligenceTaskList = this.getBusinessIntelligenceTaskList.bind(this);
        this.changeStatusAdminTenant = this.changeStatusAdminTenant.bind(this);
    }

    /**
     * 在渲染前调用,在客户端也在服务端
     */
    componentWillMount = () => {
        const params = new URLSearchParams(this.props.location.search);
        const id = params.get("id");
        this.setState({
            subjectId: id
        }, () => {
            this.getBusinessIntelligenceTaskList();
        });
    };


    /**
     * 条件
     * @param e
     * @param value
     */
    searchCondition = (value, e) => {
        this.setState({
            condition: value,
            config: {
                data: null,
                visible: false,
                title: "",
                content: ""
            }
        });
        this.pageNum = 1;
    };
    /**
     * 改变页面
     * @param currentPage
     */
    onPageChange = (currentPage) => {
        this.state = {
            current: currentPage,
            mockData: this.props.mockData,
            config: {
                data: null,
                visible: false,
                title: "",
                content: ""
            }
        };
        this.getBusinessIntelligenceTaskList();
    };

    /**
     * 改变分页的大小
     * @param pageSize
     */
    onPageSizeChange = (pageSize) => {
        this.pageSize = pageSize;
        this.pageNum = 1;
        this.getBusinessIntelligenceTaskList();
    };
    /**
     * 修改分页数据
     * @param currentPage
     */
    onChangePage = (currentPage) => {
        this.setState({
            loading: true,
            config: {
                data: null,
                visible: false,
                title: "",
                content: ""
            }
        });
        setTimeout(() => {
            this.getBusinessIntelligenceTaskList(currentPage);
            this.setState({
                loading: false,
                config: {
                    data: null,
                    visible: false,
                    title: "",
                    content: ""
                }
            });
        }, 0);
    };

    /**
     * 获取数据
     */
    getBusinessIntelligenceTaskList = (pageNum) => {
        console.log(pageNum)
        const _this = this;
        _this.pageNum = typeof (pageNum) == 'number' ? pageNum : _this.pageNum;
        let url = event.event.url + '/v1/taskDetail/getBusinessIntelligenceTaskPage';
        this.$http.post(url,
            {
                pageSize: _this.pageSize,
                pageNum: _this.pageNum,
                condition: {
                    name: _this.state.condition
                }
            })
            .then(function (response) {
                const {data} = response;
                const mockData = data.data.voList;
                _this.totalNum = data.data.total;
                mockData.forEach((o, i) => {
                    o.number = i + 1;
                });

                _this.setState({
                    mockData: mockData,
                    config: {
                        data: null,
                        visible: false,
                        title: "",
                        content: ""
                    }
                });
            })
            .catch(function (error) {
                Message.error(error.message);
            })

    };


    /**
     * 删除
     */
    changeStatusAdminTenant = (row) => {
        if (row.status === 1) {
            this.setState({
                    config: {
                        data: row,
                        visible: false,
                        title: "",
                        content: ""
                    }
                }
                , () => {
                    this.okCall(row);
                });
        } else {
            this.setState({
                    config: {
                        data: row,
                        visible: true,
                        title: "冻结租户",
                        content: "租户冻结后无法正常登录后台，您确认要冻结该租户吗？"
                    }
                }
            )
        }

    };

    /**
     * 取消按钮的操作
     */
    cancelCall = () => {
        this.setState({
            config: {
                visible: false
            }
        });
        console.log("点击取消按钮 .");
    };


    /**
     * 删除
     */
    okCall = (data) => {
        this.setState({
            config: {
                visible: false
            }
        });
        const _this = this;
        this.$http.post(event.event.url + '/v1/org/changeStatus', {id: data.id, status: data.status === 1 ? 0 : 1})
            .then(function (response) {
                const {data} = response;
                if (data.code === 1) {
                    Message.warning(data.message ? data.message : data.data);
                } else {
                    Message.success("操作成功.");
                    _this.getBusinessIntelligenceTaskList();
                }
            })
            .catch(function (error) {
                Message.error(error.message);
            })
    };


    /**
     * 批量操作
     * @param text
     */
    handleClick = () => {
        const {selectedList} = this.state;
        if (selectedList.length == 0) {
            Message.error("请选择需要删除的数据.");
            return null;
        }
        this.setState({
            visible: true
        });
    };

    /**
     *
     * @param args
     */
    onChange = (...args) => {
        this.setState({
            selectedList: args
        });
    };

    /**
     * 添加按钮
     * @param record
     */
    uploadJobZip = record => {
        this.setState({
            visibleUploadZipFileDrawer: true,
            record: record
        })
    };
    /**
     * 关闭抽屉
     */
    onDrawerClose = () => {
        this.setState({
            visibleUploadZipFileDrawer: false,
            record: {},
        });
    };


    /**
     *
     * @param file  {Object} 文件
     * @param value {Array} 值
     */
    onSuccess = (file, value) => {
        Message.success("操作成功.");
        this.onDrawerClose();
    };

    /**
     *
     * @param file  {Object} 出错的文件
     * @param fileList  {Array} 当前值
     */
    onError = (file, fileList) => {
        console.log('Exceed limit', file, fileList);
    };

    render() {
        const {mockData, record} = this.state;
        const actionUrl = event.event.url + '/v1/taskDetail/uploadFlowZipFile';
        return (
            <div>
                <Drawer
                    title="上传文件"
                    width={630}
                    onClose={this.onDrawerClose}
                    visible={this.state.visibleUploadZipFileDrawer}
                    bodyStyle={{paddingBottom: 80}}
                >
                    <Form {...formItemLayout} name="userDrawer">
                        <Form.Item
                            name="name"
                            label="可执行JOB"
                            aria-disabled={"true"}
                            rules={[
                                {
                                    required: true,
                                },
                            ]}
                        >
                            <Upload
                                headers={
                                    {
                                        'Authorization': sessionStorage.getItem("Authorization")
                                    }
                                }
                                action={actionUrl + "?taskId=" + record.id}
                                limit={1}
                                accept={"zip/*"}
                                onSuccess={this.onSuccess = this.onSuccess.bind(this)}
                                onError={this.onError = this.onError.bind(this)}>
                                <Button type="primary" style={{margin: '0 0 10px'}}>上传</Button>
                            </Upload>
                        </Form.Item>
                    </Form>
                </Drawer>
                <div className='container-header'>
                    <p>BI任务</p>
                </div>
                <Container className='container-main'>
                    <div className='container-btnBox' style={{marginTop: '0'}}>
                        <div className={styles.buttons}>
                            <Link to={"add?id="}><Button
                                className='pipe-btn-add'>新建BI任务</Button></Link>
                            <span className={styles.caseNumber}>
                                <Input onChange={this.searchCondition.bind(this)}
                                       hasClear
                                       placeholder="请输入租户代码/租户名称"
                                       className={`${styles.input} ${styles.shortInput}`}/>
                                <Button
                                    type="primary"
                                    className='pipe-btn-search'
                                    onClick={()=>this.getBusinessIntelligenceTaskList()}
                                >
                                查询
                                </Button>
                            </span>
                        </div>
                    </div>
                    <div className='container-table'>
                        <Table dataSource={mockData} size={'small'} primaryKey="id" className={styles.table}>
                            <Table.Column align="center" lock={"left"} width={50} title="序号" cell={
                                (value, index, record) => {
                                    return index + 1 + (this.pageNum - 1) * this.pageSize;
                                }
                            }/>
                            <Table.Column align="center" title="任务名称" dataIndex="name"/>
                            <Table.Column align="center" title="源数据源" dataIndex="datasourceName"/>
                            <Table.Column align="center" title="目标数据源" dataIndex="targetSourceName"/>
                            <Table.Column align="center" title="cron表达式" dataIndex="corn"/>
                            <Table.Column align="center" width={70} title="取消执行" dataIndex="cancelExec" cell={
                                (value) => {
                                    return value === 0 ? "否" : "是"
                                }

                            }/>
                            <Table.Column align="center" width={70} title="保持时间" dataIndex="holdTimeout" cell={
                                (value) => {
                                    return value ? value + "(H)" : ""
                                }

                            }/>
                            <Table.Column align="center" title="附加的条件" dataIndex="whereAnd"/>
                            <Table.Column align="center" width={120} title="下次执行时间" dataIndex="nextExecDateTime"/>
                            <Table.Column align="center" width={230} title="操作" cell={
                                (value, index, record) => {
                                    if(record.defaultValue === 0){
                                        return (
                                            <div>


                                                <Button type="normal" size="small" text className='pipe-btn-edit'>
                                                    <Link to={"add?id=" + record.id}>修改</Link>
                                                </Button>
                                                <Button type="normal" size="small" onClick={() => this.uploadJobZip(record)}
                                                        text className='pipe-btn-edit'>
                                                    上传JOB
                                                </Button>
                                                <Button type="normal" size="small" text className='pipe-btn-edit'>
                                                    <Link to={"plan?taskId=" + record.id}>执行历史</Link>
                                                </Button>
                                            </div>
                                        )
                                    }else {
                                        return (
                                            <div>

                                                <Button type="normal" size="small" onClick={() => this.uploadJobZip(record)}
                                                        text className='pipe-btn-edit'>
                                                    上传JOB
                                                </Button>
                                                <Button type="normal" size="small" text className='pipe-btn-edit'>
                                                    <Link to={"plan?taskId=" + record.id}>执行历史</Link>
                                                </Button>
                                            </div>
                                        )
                                    }
                                }
                            }/>
                        </Table>
                        <ZgDialog config={this.state.config} cancelCall={this.cancelCall} okCall={this.okCall}/>
                        <Pagination defaultCurrent={1}
                                    pageSize={this.pageSize}
                                    total={this.totalNum}
                                    onChange={this.onChangePage}
                                    onPageSizeChange={this.onPageSizeChange}
                                    pageSizeList={[5, 10, 20, 50, 100, 200]}
                                    pageSizeSelector="dropdown"
                                    hideOnlyOnePage
                                    className="page-demo"
                                    size="small"
                        />
                    </div>
                </Container>
            </div>
        )
            ;
    }

}

export default BusinessIntelligenceTaskList;
